/*
 * 描述 @login & register
 * Create by cy on 2018/10/3
 * */
const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const User = require('../../models/Users');
const keys = require('../../config/key');//拿加密姓名
const gravatar = require('gravatar');
const passport = require('passport');

/*
 * $router GET api/users/test
 * @return 返回json
 * @assess  public
 * */
router.get('/test', (req, res) => {
    res.json({
        "name":'cy'
    })
});
/*
 * $router POST api/users/register
 * @return 返回json
 * @assess  public
 * */
router.post('/register', (req, res) => {
    User.findOne({
        email: req.body.email
    }).then(user => {
        if (user) {
            return res.status(400).json('邮箱已被注册');
        } else {
            const avatar = gravatar.url(req.body.email, {s: '200', r: 'pg', d: 'mm'});
            const newUser = new User({
                name: req.body.name,
                email: req.body.email,
                avatar,
                password: req.body.password,
                identity: req.body.identity
            }).save()
                .then(user => res.json(user)).catch(err => console.log(err));
        }
    })
});
/*
 * $router POST api/users/login
 * @return 返回token jwt passport
 * @assess  public
 * */

router.post('/login', (req, res) => {
    const email = req.body.email;
    const password = req.body.password;
    //查询数据库
    User.findOne({email}).then(user => {
        if (!user) {
            return res.status(400).json('用户不存在,请先注册');
        } else if (user.password === password) {
            const rule = {//规则,这里是自定义的可以是ID或者name等
                id: user.id,
                name: user.name,
                avatar: user.avatar,
                identity: user.identity
            };
            // jwt.sign('规则','加密名字','过期时间','箭头函数')keys.secretOrKey这里可以直接是secret
            jwt.sign(rule, keys.secretOrKey, {expiresIn: 60 * 60}, (error, token) => {
                res.json({
                    success: true,
                    token: 'Bearer ' + token//Bearer不可更改  这里少个空格
                })
            });
            // return res.status(200).json('登录成功');需要注释
        } else {
            return res.status(400).json('密码错误');
        }
    })
});
/*
 * $router GET api/users/current:请求当前用户的信息,当前用户需要携带有效的token去请求
 * @return 返回 current user---验证token可以用passport和passport-jwt
 * @assess private:只有拥有token(钥匙/令牌)才能请求到当前信息
 * */
router.get('/current',passport.authenticate('jwt', {session: false}), (req, res) => {
    res.json({
        //这里能拿到的users的信息,是passport.js返回的
        id: req.user.id,
        name: req.user.name,
        email: req.user.email,
        identity: req.user.identity
    });
});
module.exports = router;
